<template>
	<view class="wrap">
		<!-- 自定义顶部导航栏 -->
		<view class="custom-app-bar-wrapper" :style="{ height: `calc(100rpx + ${statusBarHeight}px)` }">
			<view class="custom-app-bar" :style="{ top: statusBarHeight + 'px' }">
				<u-icon name="arrow-left" size="40" class="back-icon" @click="goBack"></u-icon>
				<text class="title">{{ pageTitle }}</text>
			</view>
		</view>

		<!-- 操作按钮 -->
		<view class="action-bar" :style="{ paddingTop: `calc(120rpx + ${statusBarHeight}px)` }">
			<u-button  shape="circle" v-for="(btn, index) in actions" :key="index">{{ btn.text }}</u-button>
		</view>

		<!-- 书籍列表 -->
		<view class="book-list" v-if="bookList.length > 0">
			<u-grid :col="3" :border="false">
				<u-grid-item v-for="(book, index) in bookList" :key="book.id || index">
					<view class="book-item" @click="openBookByIndex(index)">
						<view class="book-cover" :style="{ backgroundImage: `url(${book.cover})` }">
							<view class="status-tag" v-if="book.isCollect">收藏</view>
							<view class="status-tag collected" v-else-if="book.status === 'collected'">已收藏</view>
						</view>
						<text class="title-outside">{{ book.bookName }}</text>
					</view>
				</u-grid-item>
			</u-grid>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-else>
			<view class="empty-icon">📚</view>
			<text class="empty-title">暂无书籍</text>
			<text class="empty-desc">这个绘本还没有添加任何书籍内容</text>
<!--			<view class="empty-action">
				<u-button type="primary" size="small" shape="circle" @click="refreshBookList">刷新试试</u-button>
			</view>-->
		</view>
	</view>
</template>

<script>
	import * as BookApi from '@/api/book.js';

	export default {
		data() {
			return {
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight,
				pageTitle: '',
				// 绘本信息
				bookShelfInfo: {
					id: '',
					title: '',
					catalogueId: '',
					categoryName: '',
					author: ''
				},
				actions: [{
					text: '默认排序'
				}, {
					text: '书名排序'
				}, {
					text: '收藏'
				}, {
					text: '离线下载'
				}],
				// 书籍列表数据
				bookList: [],
				// 分页信息
				pageInfo: {
					pageNo: 1,
					pageSize: 20,
					total: 0
				},
				// 默认书籍列表（备用）
				defaultBookList: [{
						status: 'unread',
						icon: '👨‍👩‍👧‍👦',
						titleInside: 'MY FAMILY',
						titleOutside: 'My Family',
						color: 'linear-gradient(to top, #f0e6d2 0%, #f9f2e7 100%)'
					},
					{
						status: 'unread',
						icon: '☀️',
						titleInside: 'GOOD MORNING',
						titleOutside: 'Good Morning',
						color: 'linear-gradient(to top, #a7d8de 0%, #d8eef1 100%)'
					},
					{
						status: 'unread',
						icon: '🔢',
						titleInside: 'ONE TWO THREE',
						titleOutside: 'One, two, three',
						color: 'linear-gradient(to top, #89cff0 0%, #c4e6f7 100%)'
					},
					{
						status: 'unread',
						icon: '👫',
						titleInside: 'HOW MANY FRIENDS?',
						titleOutside: 'How many friends?',
						color: 'linear-gradient(to top, #f2a2c2 0%, #f9d8e5 100%)'
					},
					{
						status: 'unread',
						icon: '🤔',
						titleInside: 'WHO AM I?',
						titleOutside: 'Who am I',
						color: 'linear-gradient(to top, #89a3f0 0%, #c4cff7 100%)'
					},
					{
						status: 'unread',
						icon: '🐾',
						titleInside: 'ANIMALS DOING?',
						titleOutside: 'What are the animals doing?',
						color: 'linear-gradient(to top, #f0c987 0%, #f9e4c3 100%)'
					},
					{
						status: 'unread',
						icon: '💄',
						titleInside: 'AM I BEAUTIFUL?',
						titleOutside: 'Am I beautiful',
						color: 'linear-gradient(to top, #f2a2c2 0%, #f9d8e5 100%)'
					},
					{
						status: 'unread',
						icon: '🕺',
						titleInside: 'AM I HANDSOME?',
						titleOutside: 'Am I handsome',
						color: 'linear-gradient(to top, #4169e1 0%, #a2b4f0 100%)'
					},
					{
						status: 'unread',
						icon: '🍎',
						titleInside: 'I LIKE APPLES',
						titleOutside: 'I like apples',
						color: 'linear-gradient(to top, #c05f5f 0%, #e0acac 100%)'
					}
				]
			};
		},
		onLoad(options) {
			// 获取传递的参数并解码
			this.bookShelfInfo = {
				id: options.id || '',
				title: options.title ? decodeURIComponent(options.title) : '',
				catalogueId: options.catalogueId || '',
				categoryName: options.categoryName ? decodeURIComponent(options.categoryName) : '',
				author: options.author ? decodeURIComponent(options.author) : ''
			};

			// 设置页面标题
			this.pageTitle = this.bookShelfInfo.title || '书籍详情';

			// 加载书籍列表
			this.loadBookList();
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},
			// 加载书籍列表
			async loadBookList() {
				try {
					// 检查是否有绘本ID
					if (!this.bookShelfInfo.id) {
						console.warn('缺少绘本ID，使用默认数据');
						this.bookList = this.defaultBookList;
						return;
					}

					// 调用接口获取书籍列表
					const response = await BookApi.getBookList({
						pageNo: this.pageInfo.pageNo,
						pageSize: this.pageInfo.pageSize,
						bookShelfId: this.bookShelfInfo.id
					});

					if ((response.code === 200 || response.code === 0) && response.data) {
						// 处理成功响应
            this.bookList = response.data.list || [];
						this.pageInfo.total = response.data.total || 0;
					} else {
						// 接口返回失败，显示空状态
						console.warn('获取书籍列表失败');
						this.bookList = [];
					}
				} catch (error) {
					console.error('获取书籍列表出错:', error);
					// 出错时显示空状态
					this.bookList = [];
				}
			},
			// 通过索引打开书籍
			openBookByIndex(index) {
				console.log('通过索引打开书籍 - index:', index);
				console.log('书籍列表长度:', this.bookList.length);

				if (index < 0 || index >= this.bookList.length) {
					console.error('索引超出范围:', index);
					return;
				}

				const book = this.bookList[index];
				console.log('获取到的书籍对象:', book);

				this.openBook(book);
			},
			// 打开书籍
			openBook(book) {
				console.log('打开书籍 - 原始参数:', book);
				console.log('打开书籍 - 参数类型:', typeof book);
				console.log('打开书籍 - 是否为undefined:', book === undefined);

				if (!book) {
					console.error('书籍参数为空或undefined');
					return;
				}

				// 构建跳转参数
				const params = {
					bookName: encodeURIComponent(book.bookName || book.titleOutside),
					bookId: book.id || book.bookShelfId || '',
					isCollected: book.isCollect || false,
					url: encodeURIComponent(book.url || '')
				};

				// 将参数转换为URL查询字符串
				const queryString = Object.keys(params)
					.filter(key => params[key] !== '')
					.map(key => `${key}=${params[key]}`)
					.join('&');

				console.log('跳转参数:', params);

				// 跳转到图片轮播页面
				uni.navigateTo({
					url: `/pages/video/player?${queryString}`
				});
			},
			// 刷新书籍列表
			refreshBookList() {
				this.loadBookList();
			}
		}
	};
</script>

<style lang="scss">
	.wrap {
		/* padding-top: 100rpx; */ // 为自定义导航栏留出空间
		position: relative;
		padding-bottom: 20rpx;
		background-color: #fff;
	}

	.custom-app-bar-wrapper {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 100;
		background-color: #fff; // 状态栏区域的背景色
	}

	.custom-app-bar {
		position: absolute;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		height: 100rpx;
		padding: 0 20rpx;
		box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);

		.back-icon {
			padding-right: 20rpx;
		}

		.title {
			font-size: 32rpx;
			font-weight: bold;
		}
	}

	.action-bar {
		display: flex;
		justify-content: space-around;
		padding: 10rpx 0 30rpx;
	}

	.book-list {
		.u-grid-item {
			margin-bottom: 20rpx;
		}
	}

	.book-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 100%;
	}

	.book-cover {
		width: 90%;
		height: 250rpx;
		border-radius: 16rpx;
		position: relative;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
    margin-left: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
	}

	.status-tag {
		position: absolute;
		top: 0;
		left: 0;
		background-color: #fa3534;
		color: white;
		padding: 4rpx 12rpx;
		border-radius: 16rpx 0 16rpx 0;
		font-size: 20rpx;

		&.collected {
			background-color: #ff6b9d;
		}
	}

	.icon {
		font-size: 50rpx;
		margin-bottom: 10rpx;
	}

	.title-inside {
		font-size: 22rpx;
		font-weight: bold;
		color: #333;
	}

	.title-outside {
		margin-top: 10rpx;
		font-size: 24rpx;
		color: #333;
		text-align: center;
	}

	/* 空状态样式 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 40rpx;
		min-height: 400rpx;
		text-align: center;
	}

	.empty-icon {
		font-size: 120rpx;
		margin-bottom: 30rpx;
		opacity: 0.6;
	}

	.empty-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}

	.empty-desc {
		font-size: 28rpx;
		color: #999;
		line-height: 1.5;
		margin-bottom: 40rpx;
	}

	.empty-action {
		margin-top: 20rpx;
	}
</style>
